package com.shenhan.buffer;

import java.nio.IntBuffer;

/**
 * <br>
 *
 * <p>- <br>
 *
 * @author shenhan
 * @version 1.0
 * @date: 2022/5/12 15:35
 * @description:
 */
public class UseBuffer {

  static IntBuffer intBuffer = null;

  /**
   * 获取buffer实例方法
   */
  public static void allocateTest() {
    // 创建一个intBuffer实例对象
    intBuffer = IntBuffer.allocate(20);
    System.out.println("----------after allocate----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());
  }

  // 写入元素方法
  public static void putTest() {
    for (int i = 0; i < 5; i++) {
      intBuffer.put(i);
    }
    System.out.println("----------after put----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());
  }

  // 写模式 to 读模式转换
  public static void flipTest() {
    intBuffer.flip();
    System.out.println("----------after flip----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());
    // 清空
//    intBuffer.clear();
    // 压缩
//    intBuffer.compact();
  }

  public static void getTest() {
    for (int i = 0; i < 2; i++) {
      int j = intBuffer.get();
      System.out.println("j = " + j);
    }
    System.out.println("----------after get 2 int----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());

    for (int i = 0; i < 3; i++) {
      int j = intBuffer.get();
      System.out.println("j = " + j);
    }
    System.out.println("----------after get 3 int----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());
  }

  // 倒带
  public static void rewindTest() {
    intBuffer.rewind();
    System.out.println("----------after rewind----------");
    System.out.println("position = " + intBuffer.position());
    System.out.println("limit = " + intBuffer.limit());
    System.out.println("capacity = " + intBuffer.capacity());
  }

  // mark() 和 reset()

  public static void main(String[] args) {
    allocateTest();
    putTest();
    flipTest();
    getTest();
    rewindTest();
    getTest();
  }
}
